package com.my.processor.test.two;

import com.google.auto.service.AutoService;
import com.my.processor.common.AbstractLogProcessor;

import javax.annotation.processing.Processor;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.annotation.processing.SupportedSourceVersion;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
import javax.tools.Diagnostic;
import java.util.Set;

/**
 * 1.自定义Annotation Processor需要继承AbstractProcessor，并覆写process方法。
 * 2.需要声明此Processor所支持处理的注解类
 * @SupportedAnnotationTypes({"com.processor.TestAnnotation"})
 * （类名需要已字符串形式填入包名+类名，否则不起作用）
 * 3.需要声明注解作用的java版本，由于我的工程默认使用了JDK 7进行编译，因此需要填写  by-timo:没加暂时没发现问题
 * @SupportedSourceVersion(SourceVersion.RELEASE_7)
 *
 * @author timo 2021/2/19
 */
@SupportedAnnotationTypes({"com.my.processor.test.two.TestAnnotation"})
@SupportedSourceVersion(SourceVersion.RELEASE_8)
@AutoService(Processor.class)
public class MyProcessor2 extends AbstractLogProcessor {

    @Override
    protected boolean processImpl(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
        log("MyProcessor2 - roundEnv:"+roundEnv.toString());
        for (TypeElement element : annotations) {
            log("MyProcessor2 - 注解类型:"+element.getSimpleName().toString());
        }
        // 遍历annotations获取annotation类型
        for (TypeElement typeElement : annotations) {
            // 使用roundEnv.getElementsAnnotatedWith获取所有被某一类型注解标注的元素，依次遍历
            for (Element element : roundEnv.getElementsAnnotatedWith(typeElement)) {
                // 在元素上调用接口获取注解值
                int annoValue = element.getAnnotation(TestAnnotation.class).value();
                String annoWhat = element.getAnnotation(TestAnnotation.class).what();
                log("MyProcessor2 - value = " + annoValue + "  what = " + annoWhat);
                // 向当前环境输出warning信息
                processingEnv.getMessager().printMessage(Diagnostic.Kind.WARNING, "value = " + annoValue + ", what = " + annoWhat, element);
            }
        }
        return true;
    }


}
